package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.ServiceException;
import com.zzyl.nursing.service.WeChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class WeChatServiceImpl implements WeChatService {


    private static final String OPEN_ID_URL= "https://api.weixin.qq.com/sns/jscode2session";

    private  static final String appid= "wxde3620527edae19b";

    private static final String secret ="900a593af0605e0d18f2d4081e0fd276";

    private static final String GET_PHONE_URL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={}";

    private  static final String GET_ACCESS_TOKEN_URL = "https://api.weixin.qq.com/cgi-bin/token";


    @Override
    public String getOpenID(String code) {
        Map<String, Object> openIDMap = new HashMap<>();
        openIDMap.put("appid", appid);
        openIDMap.put("secret", secret);
        openIDMap.put("js_code",code);
        openIDMap.put("grant_type","authorization_code");
        try {

        String openIdInfo = HttpUtil.get(OPEN_ID_URL, openIDMap);
            log.info("获取openid：{}",openIdInfo);
            JSONObject entries = JSONUtil.parseObj(openIdInfo);
            String openid = entries.getStr("openid");
            return openid;
        } catch (Exception e) {
            throw new ServiceException("获取OpenID失败，请稍后重试");
        }

    }

    @Override
    public String getPhone(String phoneCode) {

        String accessToken = getAccessToken();
        String url = StrUtil.format(GET_PHONE_URL, accessToken);
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", phoneCode);
        HttpResponse res = HttpRequest.post(url).body(JSONUtil.toJsonStr(paramMap)).timeout(5000).execute();
        if(res.isOk()) {
            String result = res.body();
            log.info("获取手机号: {}", result);
            //解析json对象
            JSONObject jsonObject = JSONUtil.parseObj(result);
            String phoneNumber = jsonObject.getJSONObject("phone_info").getStr("phoneNumber");
            //如果为空，说明出错了，微信报错信息里才拿不到openid，这时需要看上面 记录的日志信息
            if(StrUtil.isNotBlank(phoneNumber)) {
                return phoneNumber;
            }
        }
        throw new ServiceException("获取手机号失败，请稍后重试");
    }

    @Override
    public String getAccessToken() {

        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", appid);
        paramMap.put("secret", secret);
        paramMap.put("grant_type", "client_credential");
        HttpResponse res = HttpRequest.get(GET_ACCESS_TOKEN_URL).form(paramMap).timeout(5000).execute();
        if(res.isOk()) {
            String result = res.body();
            log.info("获取access_token: {}", result);
            //解析json对象
            JSONObject jsonObject = JSONUtil.parseObj(result);
            String access_token= jsonObject.getStr("access_token");
            //如果为空，说明出错了，微信报错信息里才拿不到openid，这时需要看上面 记录的日志信息
            if(StrUtil.isNotBlank(access_token)) {
                return access_token;
            }
        }
        throw new ServiceException("获取access_token失败，请稍后重试");
    }


}
